<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Exception\Handler;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use App\Utils\ServerUtil;

class AppExceptionHandler extends ExceptionHandler
{
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $err = $throwable->getMessage();
        if (strpos($err, \config('web.err_msg_splite')) !== false) {
            $err_arr = \explode(\config('web.err_msg_splite'), $err);
            $web_err = $err_arr[0];
        } else {
            $web_err = '网络异常,请稍后再试';
        }
        $data = json_encode([
            'errCode' => 500,
            'msg' => $web_err,
            'data'=>[],
        ], JSON_UNESCAPED_UNICODE);
        ServerUtil::info('网络异常,请稍后再试'.$err, ['line'=>$throwable->getLine(),'file'=>$throwable->getFile()]);
        // $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        // $this->logger->error($throwable->getTraceAsString());
        return $response->withStatus(200)->withBody(new SwooleStream($data));
        //return $response->withHeader("Server", "Hyperf")->withStatus(500)->withBody(new SwooleStream('Internal Server Error.'));
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
